<script setup lang="ts">
import { ref, reactive, onMounted, nextTick, computed, onUnmounted } from "vue";
import { useRouter } from "vue-router";
import * as echarts from "echarts";
import {
  getRiskOverview,
  batchScoreAllCompliance,
  getScoreTaskStatus,
  calculateAssetScore,
} from "../servers";
import { getTemplateList } from "../servers";
import {
  ElMessage,
  ElMessageBox,
  ElProgress,
  ElSelect,
  ElOption,
  ElIcon,
  ElTag,
  ElDialog,
} from "element-plus";
import {
  Refresh,
  Download,
  VideoPlay,
  Document,
  Setting,
  InfoFilled,
} from "@element-plus/icons-vue";

const router = useRouter();

const loading = ref(false);
const lastUpdateTime = ref<string>("");

// 一键评分任务相关
const showScoreProgress = ref(false); // 控制是否显示进度卡片
const batchScoreLoading = ref(false); // 按钮单独的loading状态
const showTemplateSelectDialog = ref(false); // 模板选择对话框
const selectedTemplateId = ref<number | null>(null); // 选中的模板ID
const templateList = ref<any[]>([]); // 模板列表
const templateListLoading = ref(false); // 模板列表loading
const scoreTaskStatus = reactive({
  task_id: "",
  status: "" as "running" | "completed" | "failed" | "cancelled",
  progress: 0,
  total: 0,
  completed: 0, // 成功数量
  processed: 0, // 已处理数量
  failed: 0,
  estimated_remaining_time: "",
  started_at: "",
  completed_at: "",
  error_message: "",
});
let scoreTaskTimer: ReturnType<typeof setInterval> | null = null;

// 单个资产评分相关
const scoringIPs = ref<Set<string>>(new Set());

// 统计数据
const overview = reactive({
  total_assets: 0,
  average_score: 0,
  risk_distribution: {
    critical: 0,
    high: 0,
    medium: 0,
    low: 0,
    safe: 0,
  } as Record<string, number>,
  trend_data: [] as Array<{ date: string; average_score: number }>,
  dimension_average_deduction: {
    compliance_status: 0,
    vulnerability_risk: 0,
    intelligence_match: 0,
    high_risk_port: 0,
    local_remote_diff: 0,
    domain_weight: 0,
  } as Record<string, number>,
  top_risk_assets: [] as Array<{
    asset_ip: string;
    risk_level: string;
    total_score: number;
    department: string;
    calculated_at: string;
  }>,
  // 较昨日对比数据
  compare_yesterday: {
    total_assets: 0,
    high_risk: 0,
    medium_risk: 0,
    average_score: 0,
  } as Record<string, number>,
});

// 趋势图时间范围
const trendDays = ref(30);

// 图表引用
const pieRef = ref<HTMLDivElement>();
const trendRef = ref<HTMLDivElement>();
const radarRef = ref<HTMLDivElement>();
let pieChart: echarts.ECharts | null = null;
let trendChart: echarts.ECharts | null = null;
let radarChart: echarts.ECharts | null = null;

// 风险等级颜色映射
const riskLevelColors: Record<string, string> = {
  critical: "#f5222d", // 严重-红色
  high: "#fa8c16", // 高危-橙色
  medium: "#faad14", // 中危-黄色
  low: "#52c41a", // 低危-绿色
  safe: "#1890ff", // 安全-蓝色
};

const riskLevelNames: Record<string, string> = {
  critical: "严重",
  high: "高危",
  medium: "中危",
  low: "低危",
  safe: "安全",
};

// 初始化饼图
const initPie = () => {
  if (!pieRef.value) return;
  if (pieChart) {
    pieChart.dispose();
  }
  pieChart = echarts.init(pieRef.value);
  const dist = overview.risk_distribution || ({} as any);

  const pieData = [
    {
      name: "严重",
      value: dist.critical || 0,
      itemStyle: { color: riskLevelColors.critical },
    },
    {
      name: "高危",
      value: dist.high || 0,
      itemStyle: { color: riskLevelColors.high },
    },
    {
      name: "中危",
      value: dist.medium || 0,
      itemStyle: { color: riskLevelColors.medium },
    },
    {
      name: "低危",
      value: dist.low || 0,
      itemStyle: { color: riskLevelColors.low },
    },
    {
      name: "安全",
      value: dist.safe || 0,
      itemStyle: { color: riskLevelColors.safe },
    },
  ];

  pieChart.setOption({
    tooltip: {
      trigger: "item",
      formatter: (params: any) => {
        const total = pieData.reduce((sum, item) => sum + item.value, 0);
        const percentage =
          total > 0 ? ((params.value / total) * 100).toFixed(1) : 0;
        return `${params.name}: ${params.value} (${percentage}%)`;
      },
    },
    legend: {
      bottom: 0,
      left: "center",
    },
    series: [
      {
        type: "pie",
        radius: ["40%", "70%"],
        avoidLabelOverlap: false,
        center: ["50%", "45%"],
        label: {
          show: true,
          formatter: "{b}: {c}",
        },
        emphasis: {
          label: {
            show: true,
            fontSize: 14,
            fontWeight: "bold",
          },
        },
        labelLine: {
          show: true,
        },
        data: pieData,
      },
    ],
    graphic: [
      {
        type: "text",
        left: "center",
        top: "45%",
        style: {
          text: "平均评分",
          textAlign: "center",
          fill: "#666",
          fontSize: 14,
        },
      },
      {
        type: "text",
        left: "center",
        top: "50%",
        style: {
          text: overview.average_score.toFixed(2),
          textAlign: "center",
          fill: "#1890ff",
          fontSize: 24,
          fontWeight: "bold",
        },
      },
    ],
  });
};

// 初始化趋势图
const initTrend = () => {
  if (!trendRef.value) return;
  if (trendChart) {
    trendChart.dispose();
  }
  trendChart = echarts.init(trendRef.value);

  const trendData = overview.trend_data || [];
  const filteredData = trendData.slice(-trendDays.value);

  const dates = filteredData.map((item) => item.date);
  const scores = filteredData.map((item) => item.average_score);

  trendChart.setOption({
    tooltip: {
      trigger: "axis",
      formatter: (params: any) => {
        const param = params[0];
        return `${param.name}<br/>评分: ${param.value.toFixed(2)} 分`;
      },
    },
    grid: {
      left: "3%",
      right: "4%",
      bottom: "3%",
      containLabel: true,
    },
    xAxis: {
      type: "category",
      boundaryGap: false,
      data: dates,
      axisLabel: {
        formatter: (value: string) => {
          // 格式化日期显示
          if (value) {
            const date = new Date(value);
            return `${date.getMonth() + 1}/${date.getDate()}`;
          }
          return value;
        },
      },
    },
    yAxis: {
      type: "value",
      min: 0,
      max: 100,
      interval: 10,
      axisLabel: {
        formatter: "{value} 分",
      },
    },
    series: [
      {
        name: "平均评分",
        type: "line",
        data: scores,
        smooth: true,
        lineStyle: {
          color: "#1890ff",
          width: 2,
        },
        areaStyle: {
          color: {
            type: "linear",
            x: 0,
            y: 0,
            x2: 0,
            y2: 1,
            colorStops: [
              { offset: 0, color: "rgba(24, 144, 255, 0.3)" },
              { offset: 1, color: "rgba(24, 144, 255, 0.1)" },
            ],
          },
        },
        symbol: "circle",
        symbolSize: 6,
        itemStyle: {
          color: "#1890ff",
        },
      },
    ],
  });
};

// 初始化雷达图
const initRadar = () => {
  if (!radarRef.value) return;
  if (radarChart) {
    radarChart.dispose();
  }
  radarChart = echarts.init(radarRef.value);

  const deduction = overview.dimension_average_deduction || {};

  const indicator = [
    { name: "合规状态", max: 25 },
    { name: "漏洞风险", max: 25 },
    { name: "威胁情报", max: 25 },
    { name: "高危端口", max: 25 },
    { name: "本异地差异", max: 25 },
    { name: "域名权重", max: 25 },
  ];

  radarChart.setOption({
    tooltip: {
      trigger: "item",
      formatter: (params: any) => {
        return `${params.name}<br/>扣分: ${params.value.toFixed(2)}`;
      },
    },
    radar: {
      indicator: indicator,
      center: ["50%", "55%"],
      radius: "65%",
      name: {
        fontSize: 14,
        fontWeight: "bold",
        color: "#303133", // 深灰色文字
      },
      splitArea: {
        areaStyle: {
          color: ["rgba(64, 158, 255, 0.1)", "rgba(64, 158, 255, 0.05)"], // 更深的蓝色背景
        },
      },
      axisLine: {
        lineStyle: {
          color: "#409EFF", // 蓝色轴线，对比度高
          width: 1,
        },
      },
      splitLine: {
        lineStyle: {
          color: "#409EFF", // 蓝色网格线，对比度高
          width: 1,
          type: "dashed", // 虚线样式
        },
      },
    },
    series: [
      {
        name: "平均扣分",
        type: "radar",
        lineStyle: {
          color: "#ff7875",
          width: 2, // 增加线条宽度
        },
        data: [
          {
            value: [
              deduction.compliance_status || 0,
              deduction.vulnerability_risk || 0,
              deduction.intelligence_match || 0,
              deduction.high_risk_port || 0,
              deduction.local_remote_diff || 0,
              deduction.domain_weight || 0,
            ],
            name: "平均扣分",
            itemStyle: {
              color: "#ff7875",
              borderWidth: 2,
            },
            areaStyle: {
              color: "rgba(255, 120, 117, 0.3)", // 增加填充透明度
            },
          },
        ],
      },
    ],
  });
};

// 刷新数据
const refresh = async () => {
  loading.value = true;
  try {
    const { data } = await getRiskOverview({});
    if (!data) {
      ElMessage.error("获取数据失败");
      return;
    }

    overview.total_assets = data.total_assets || 0;
    overview.average_score = data.average_score || 0;
    overview.risk_distribution = data.risk_distribution || {
      critical: 0,
      high: 0,
      medium: 0,
      low: 0,
      safe: 0,
    };
    overview.trend_data = data.trend_data || [];
    overview.dimension_average_deduction = data.dimension_average_deduction || {
      compliance_status: 0,
      vulnerability_risk: 0,
      intelligence_match: 0,
      high_risk_port: 0,
      local_remote_diff: 0,
      domain_weight: 0,
    };
    overview.top_risk_assets = data.top_risk_assets || [];
    lastUpdateTime.value = data.last_update_time || "";
    // 较昨日对比数据（如果接口返回）
    overview.compare_yesterday = data.compare_yesterday || {
      total_assets: 0,
      high_risk: 0,
      medium_risk: 0,
      average_score: 0,
    };

    await nextTick();
    initPie();
    initTrend();
    initRadar();
  } catch (e: any) {
    console.error("获取数据失败:", e);
    ElMessage.error(e?.message || "获取数据失败");
  } finally {
    loading.value = false;
  }
};

// 导出数据
const handleExport = () => {
  ElMessage.info("导出功能开发中...");
};

// 获取模板列表
const fetchTemplateList = async () => {
  templateListLoading.value = true;
  try {
    const { data } = await getTemplateList({
      page: 1,
      page_size: 100, // 获取足够多的模板
      filters: {
        is_active: true, // 只获取启用的模板
      },
    });
    templateList.value = data.items || [];
  } catch (error) {
    console.error("获取模板列表失败:", error);
    ElMessage.error("获取模板列表失败");
  } finally {
    templateListLoading.value = false;
  }
};

// 打开模板选择对话框
const openTemplateSelectDialog = async () => {
  showTemplateSelectDialog.value = true;
  selectedTemplateId.value = null;
  if (templateList.value.length === 0) {
    await fetchTemplateList();
  }
};

// 确认选择模板并启动评分
const confirmBatchScore = async () => {
  if (!selectedTemplateId.value) {
    ElMessage.warning("请选择评分模板");
    return;
  }

  try {
    await ElMessageBox.confirm(
      "确定要对所有资产进行评分吗？此操作可能需要较长时间，建议在非高峰时段执行。",
      "确认一键评分",
      {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      }
    );

    showTemplateSelectDialog.value = false;
    batchScoreLoading.value = true;

    // 启动评分任务
    const { data } = await batchScoreAllCompliance({
      template_id: selectedTemplateId.value,
    });
    if (!data || !data.task_id) {
      ElMessage.error("启动评分任务失败");
      return;
    }

    // 初始化任务状态 - 映射返回的字段
    scoreTaskStatus.task_id = data.task_id;
    scoreTaskStatus.status = (data.task_status || "running") as
      | "running"
      | "completed"
      | "failed"
      | "cancelled";
    scoreTaskStatus.total = data.total_count || 0;
    scoreTaskStatus.completed = data.success_count || 0;
    scoreTaskStatus.processed = data.processed_count || 0;
    scoreTaskStatus.failed = data.fail_count || 0;
    scoreTaskStatus.progress = data.progress_percent || 0;
    scoreTaskStatus.started_at = data.started_at || "";
    scoreTaskStatus.completed_at = data.completed_at || "";
    scoreTaskStatus.error_message = data.error_message || "";
    showScoreProgress.value = true;

    // 开始轮询任务状态
    startPollingTaskStatus(data.task_id);
  } catch (e: any) {
    if (e !== "cancel") {
      console.error("启动评分任务失败:", e);
      ElMessage.error(e?.message || "启动评分任务失败");
    }
  } finally {
    batchScoreLoading.value = false;
  }
};

// 一键评分所有资产 - 打开模板选择对话框
const handleBatchScoreAll = () => {
  openTemplateSelectDialog();
};

// 开始轮询任务状态
const startPollingTaskStatus = (taskId: string) => {
  // 清除之前的定时器
  if (scoreTaskTimer) {
    clearInterval(scoreTaskTimer);
  }

  // 立即查询一次
  pollTaskStatus(taskId);

  // 每3秒查询一次
  scoreTaskTimer = setInterval(() => {
    pollTaskStatus(taskId);
  }, 3000);
};

// 轮询任务状态
const pollTaskStatus = async (taskId: string) => {
  try {
    const { data } = await getScoreTaskStatus(taskId);
    if (!data) {
      return;
    }

    // 更新任务状态 - 映射返回的字段
    scoreTaskStatus.status = (data.task_status || "running") as
      | "running"
      | "completed"
      | "failed"
      | "cancelled";
    scoreTaskStatus.progress = data.progress_percent || 0;
    scoreTaskStatus.completed = data.success_count || 0;
    scoreTaskStatus.processed = data.processed_count || 0;
    scoreTaskStatus.failed = data.fail_count || 0;
    scoreTaskStatus.total = data.total_count || scoreTaskStatus.total;
    scoreTaskStatus.started_at = data.started_at || scoreTaskStatus.started_at;
    scoreTaskStatus.completed_at =
      data.completed_at || scoreTaskStatus.completed_at;
    scoreTaskStatus.error_message =
      data.error_message || scoreTaskStatus.error_message;
    scoreTaskStatus.estimated_remaining_time =
      data.estimated_remaining_time || "";

    // 任务完成
    if (data.task_status === "completed") {
      stopPollingTaskStatus();
      ElMessage.success(
        `评分任务已完成！成功: ${scoreTaskStatus.completed.toLocaleString()}，失败: ${scoreTaskStatus.failed.toLocaleString()}`
      );
      // 刷新仪表板数据
      await refresh();
      // 不自动关闭进度卡片，让用户手动关闭
    } else if (data.task_status === "failed") {
      stopPollingTaskStatus();
      const errorMsg = data.error_message || "评分任务执行失败";
      ElMessage.error(errorMsg);
    } else if (data.task_status === "cancelled") {
      stopPollingTaskStatus();
      ElMessage.info("评分任务已取消");
    }
  } catch (e: any) {
    console.error("查询任务状态失败:", e);
    // 不显示错误，避免频繁弹窗
  }
};

// 停止轮询
const stopPollingTaskStatus = () => {
  if (scoreTaskTimer) {
    clearInterval(scoreTaskTimer);
    scoreTaskTimer = null;
  }
};

// 停止监控任务
const handleStopMonitoring = () => {
  stopPollingTaskStatus();
  ElMessage.info("已停止任务状态监控");
  // 不隐藏卡片，让用户能看到最终状态
};

// 单个资产评分
const handleScoreAsset = async (assetIp: string) => {
  try {
    // 添加到loading集合
    scoringIPs.value.add(assetIp);

    const { data } = await calculateAssetScore({
      asset_ip: assetIp,
      include_remediation: false,
    });

    if (data) {
      ElMessage.success(
        `资产 ${assetIp} 评分成功！评分: ${
          data.total_score?.toFixed(2) || "N/A"
        }`
      );
      // 刷新仪表板数据
      await refresh();
    } else {
      ElMessage.error("评分失败，请稍后重试");
    }
  } catch (e: any) {
    console.error("评分失败:", e);
    ElMessage.error(e?.message || `资产 ${assetIp} 评分失败`);
  } finally {
    // 移除loading状态
    scoringIPs.value.delete(assetIp);
  }
};

// 切换趋势图时间范围
const handleTrendDaysChange = (days: number) => {
  trendDays.value = days;
  initTrend();
};

// 查看资产详情
const handleViewAssetDetail = (assetIp: string) => {
  if (!assetIp) {
    ElMessage.warning("资产IP不能为空");
    return;
  }
  router.push({
    name: "asset-detail",
    query: {
      ip: assetIp,
    },
  });
};

// 计算高风险资产数（critical + high）
const highRiskCount = computed(() => {
  return (
    (overview.risk_distribution.critical || 0) +
    (overview.risk_distribution.high || 0)
  );
});

// 获取风险等级显示
const getRiskLevelDisplay = (level: string) => {
  const levelMap: Record<
    string,
    { label: string; color: string; icon: string }
  > = {
    critical: { label: "严重", color: "#f5222d", icon: "🔴" },
    high: { label: "高危", color: "#fa8c16", icon: "🟠" },
    medium: { label: "中危", color: "#faad14", icon: "🟡" },
    low: { label: "低危", color: "#52c41a", icon: "🟢" },
    safe: { label: "安全", color: "#1890ff", icon: "🔵" },
  };
  return levelMap[level] || { label: level, color: "#666", icon: "" };
};

// 格式化较昨日对比数据
const formatCompare = (value: number): string => {
  if (value === 0) return "±0";
  if (value > 0) return `+${value}`;
  return `${value}`;
};

// 格式化较昨日对比数据（小数）
const formatCompareDecimal = (value: number): string => {
  if (value === 0) return "±0";
  if (value > 0) return `+${value.toFixed(2)}`;
  return value.toFixed(2);
};

onMounted(() => {
  refresh();
});

// 组件卸载时销毁图表和定时器
onUnmounted(() => {
  if (pieChart) {
    pieChart.dispose();
    pieChart = null;
  }
  if (trendChart) {
    trendChart.dispose();
    trendChart = null;
  }
  if (radarChart) {
    radarChart.dispose();
    radarChart = null;
  }
  // 清除任务状态轮询
  stopPollingTaskStatus();
});
</script>

<script lang="ts">
export default {
  name: "RiskOverviewDashboard",
};
</script>

<template>
  <div v-loading="loading" class="risk-overview-dashboard">
    <!-- 快速操作区 -->
    <el-card shadow="never" class="action-card" style="margin-bottom: 16px">
      <div class="action-buttons">
        <el-button
          type="primary"
          :loading="batchScoreLoading"
          @click="handleBatchScoreAll"
        >
          一键评分所有资产
        </el-button>
        <!-- <el-button
          :icon="Document"
          @click="() => ElMessage.info('查看详细报告功能开发中...')"
        >
          查看详细报告
        </el-button>
        <el-button @click="() => ElMessage.info('模板管理功能开发中...')">
          模板管理
        </el-button>
        <el-button @click="handleExport"> 导出统计数据 </el-button> -->
      </div>
    </el-card>

    <!-- 一键评分进度卡片 -->
    <el-card
      v-if="showScoreProgress"
      shadow="never"
      class="score-progress-card"
      style="margin-bottom: 16px"
    >
      <template #header>
        <div class="card-header">
          <span>🚀 一键评分任务进度</span>
          <el-button
            v-if="scoreTaskStatus.status === 'running'"
            @click="handleStopMonitoring"
          >
            停止监控
          </el-button>
          <el-button
            v-if="
              scoreTaskStatus.status === 'completed' ||
              scoreTaskStatus.status === 'failed' ||
              scoreTaskStatus.status === 'cancelled'
            "
            link
            size="small"
            @click="showScoreProgress = false"
          >
            关闭
          </el-button>
        </div>
      </template>
      <div class="score-progress-content">
        <div class="progress-info">
          <div class="info-item">
            <span class="label">任务ID:</span>
            <span class="value">{{ scoreTaskStatus.task_id }}</span>
          </div>
          <div class="info-item">
            <span class="label">任务状态:</span>
            <el-tag
              :type="
                scoreTaskStatus.status === 'completed'
                  ? 'success'
                  : scoreTaskStatus.status === 'failed'
                  ? 'danger'
                  : scoreTaskStatus.status === 'cancelled'
                  ? 'info'
                  : 'warning'
              "
            >
              {{
                scoreTaskStatus.status === "running"
                  ? "运行中"
                  : scoreTaskStatus.status === "completed"
                  ? "已完成"
                  : scoreTaskStatus.status === "failed"
                  ? "失败"
                  : "已取消"
              }}
            </el-tag>
          </div>
        </div>

        <el-progress
          :percentage="scoreTaskStatus.progress"
          :status="
            scoreTaskStatus.status === 'completed'
              ? 'success'
              : scoreTaskStatus.status === 'failed'
              ? 'exception'
              : undefined
          "
          style="margin: 20px 0"
        />

        <div class="progress-stats">
          <div class="stat-item">
            <span class="stat-label">总数:</span>
            <span class="stat-value">{{
              scoreTaskStatus.total.toLocaleString()
            }}</span>
          </div>
          <div class="stat-item">
            <span class="stat-label">已处理:</span>
            <span class="stat-value">{{
              scoreTaskStatus.processed.toLocaleString()
            }}</span>
          </div>
          <div class="stat-item">
            <span class="stat-label">成功:</span>
            <span class="stat-value success">{{
              scoreTaskStatus.completed.toLocaleString()
            }}</span>
          </div>
          <div class="stat-item">
            <span class="stat-label">失败:</span>
            <span class="stat-value danger">{{
              scoreTaskStatus.failed.toLocaleString()
            }}</span>
          </div>
        </div>
        <div
          class="progress-info"
          style="
            margin-top: 12px;
            padding-top: 12px;
            border-top: 1px solid #f0f0f0;
          "
        >
          <div class="info-item" v-if="scoreTaskStatus.started_at">
            <span class="label">开始时间:</span>
            <span class="value">{{ scoreTaskStatus.started_at }}</span>
          </div>
          <div class="info-item" v-if="scoreTaskStatus.completed_at">
            <span class="label">完成时间:</span>
            <span class="value">{{ scoreTaskStatus.completed_at }}</span>
          </div>
          <div class="info-item" v-if="scoreTaskStatus.error_message">
            <span class="label" style="color: #ff4d4f">错误信息:</span>
            <span class="value" style="color: #ff4d4f">{{
              scoreTaskStatus.error_message
            }}</span>
          </div>
        </div>
      </div>
    </el-card>

    <!-- 页面标题区 -->
    <div class="page-header">
      <div class="header-left">
        <h2>📊 风险评分概览</h2>
      </div>
      <div class="header-right">
        <span class="update-time" v-if="lastUpdateTime">
          最后更新: {{ lastUpdateTime }}
        </span>
        <el-button type="primary" @click="refresh">刷新</el-button>
        <!-- <el-button :icon="Download" @click="handleExport">导出</el-button> -->
      </div>
    </div>

    <!-- 统计卡片区 -->
    <div class="kpi-cards">
      <el-card shadow="never" class="kpi">
        <div class="kpi-icon">📦</div>
        <div class="kpi-title">总资产数</div>
        <div class="kpi-value">
          {{ overview.total_assets.toLocaleString() }}
        </div>
        <div class="kpi-unit">个资产</div>
        <div class="kpi-compare">
          较昨日 {{ formatCompare(overview.compare_yesterday.total_assets) }}
        </div>
      </el-card>
      <el-card shadow="never" class="kpi">
        <div class="kpi-icon">🔴</div>
        <div class="kpi-title">高风险资产</div>
        <div class="kpi-value">{{ highRiskCount }}</div>
        <div class="kpi-unit">个资产</div>
        <div class="kpi-compare">
          较昨日 {{ formatCompare(overview.compare_yesterday.high_risk) }}
        </div>
      </el-card>
      <el-card shadow="never" class="kpi">
        <div class="kpi-icon">🟡</div>
        <div class="kpi-title">中风险资产</div>
        <div class="kpi-value">
          {{ overview.risk_distribution.medium || 0 }}
        </div>
        <div class="kpi-unit">个资产</div>
        <div class="kpi-compare">
          较昨日 {{ formatCompare(overview.compare_yesterday.medium_risk) }}
        </div>
      </el-card>
      <el-card shadow="never" class="kpi">
        <div class="kpi-icon">📊</div>
        <div class="kpi-title">平均评分</div>
        <div class="kpi-value">{{ overview.average_score.toFixed(2) }}</div>
        <div class="kpi-unit">分</div>
        <div class="kpi-compare">
          较昨日
          {{ formatCompareDecimal(overview.compare_yesterday.average_score) }}
        </div>
      </el-card>
    </div>

    <!-- 第一行图表区 -->
    <div class="chart-row">
      <el-card shadow="never" class="chart-card">
        <template #header>
          <div class="card-header">📊 风险等级分布</div>
        </template>
        <div ref="pieRef" style="height: 320px"></div>
      </el-card>

      <el-card shadow="never" class="chart-card">
        <template #header>
          <div class="card-header">
            📈 评分趋势（近{{ trendDays }}天）
            <div class="header-actions">
              <!-- <el-button-group>
                <el-button
                  :type="trendDays === 7 ? 'primary' : 'default'"
                  size="small"
                  @click="handleTrendDaysChange(7)"
                  >7天</el-button
                >
                <el-button
                  :type="trendDays === 30 ? 'primary' : 'default'"
                  size="small"
                  @click="handleTrendDaysChange(30)"
                  >30天</el-button
                >
                <el-button
                  :type="trendDays === 90 ? 'primary' : 'default'"
                  size="small"
                  @click="handleTrendDaysChange(90)"
                  >90天</el-button
                >
              </el-button-group> -->
            </div>
          </div>
        </template>
        <div ref="trendRef" style="height: 320px"></div>
      </el-card>
      <el-card shadow="never" class="chart-card">
        <template #header>
          <div class="card-header">🎯 各维度平均扣分分析</div>
        </template>
        <div ref="radarRef" style="height: 400px"></div>
      </el-card>
    </div>

    <!-- 第二行图表区 - 雷达图 -->
    <!-- <div class="chart-row">
      <el-card shadow="never" class="chart-card full-width">
        <template #header>
          <div class="card-header">🎯 各维度平均扣分分析</div>
        </template>
        <div ref="radarRef" style="height: 400px"></div>
      </el-card>
    </div> -->

    <!-- TOP10 高风险资产列表 -->
    <el-card shadow="never" class="table-card">
      <template #header>
        <div class="card-header">
          ⚠️ TOP10 高风险资产（排除安全资产）
          <!-- <div class="header-actions">
            <el-button size="small" type="primary" link>查看全部</el-button>
            <el-button size="small" type="primary" link @click="handleExport"
              >导出列表</el-button
            >
          </div> -->
        </div>
      </template>
      <el-table :data="overview.top_risk_assets" border stripe>
        <el-table-column label="排名" width="70" align="center">
          <template #default="{ $index }">
            {{ $index + 1 }}
          </template>
        </el-table-column>
        <el-table-column prop="asset_ip" label="IP地址" width="150" />
        <el-table-column prop="department" label="部门" />
        <el-table-column label="风险等级" width="120" align="center">
          <template #default="{ row }">
            <el-tag
              :type="
                row.risk_level === 'critical' || row.risk_level === 'high'
                  ? 'danger'
                  : row.risk_level === 'medium'
                  ? 'warning'
                  : row.risk_level === 'low'
                  ? 'success'
                  : 'info'
              "
              size="small"
            >
              {{ getRiskLevelDisplay(row.risk_level).icon }}
              {{ getRiskLevelDisplay(row.risk_level).label }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column
          prop="total_score"
          label="评分"
          width="100"
          align="center"
        >
          <template #default="{ row }">
            {{ row.total_score.toFixed(2) }}
          </template>
        </el-table-column>
        <el-table-column
          prop="calculated_at"
          label="上次评分时间"
          width="180"
        />
        <el-table-column label="操作" width="150" align="center">
          <template #default="{ row }">
            <el-button
              type="primary"
              link
              size="small"
              :loading="scoringIPs.has(row.asset_ip)"
              @click="() => handleScoreAsset(row.asset_ip)"
            >
              重新评分
            </el-button>
            <el-button
              link
              size="small"
              @click="() => handleViewAssetDetail(row.asset_ip)"
            >
              详情
            </el-button>
          </template>
        </el-table-column>
      </el-table>
      <div v-if="overview.top_risk_assets.length === 0" class="empty-table">
        暂无更多高风险资产
      </div>
    </el-card>

    <!-- 模板选择对话框 -->
    <el-dialog
      v-model="showTemplateSelectDialog"
      title="选择评分模板"
      width="500px"
      destroy-on-close
    >
      <div v-loading="templateListLoading">
        <el-select
          v-model="selectedTemplateId"
          placeholder="请选择评分模板"
          style="width: 100%"
          filterable
        >
          <el-option
            v-for="template in templateList"
            :key="template.id"
            :label="`${template.template_name} (${template.template_code})`"
            :value="template.id"
          >
            <div
              style="
                display: flex;
                justify-content: space-between;
                align-items: center;
              "
            >
              <span>{{ template.template_name }}</span>
              <el-tag
                v-if="template.is_default"
                type="warning"
                size="small"
                style="margin-left: 8px"
              >
                默认
              </el-tag>
            </div>
          </el-option>
        </el-select>
        <div
          style="
            margin-top: 12px;
            color: #86909c;
            font-size: 13px;
            display: flex;
            align-items: center;
            gap: 4px;
          "
        >
          <el-icon><InfoFilled /></el-icon>
          <span
            >请选择要使用的评分模板，系统将使用该模板对所有资产进行评分</span
          >
        </div>
      </div>
      <template #footer>
        <el-button @click="showTemplateSelectDialog = false">取消</el-button>
        <el-button
          type="primary"
          @click="confirmBatchScore"
          :disabled="!selectedTemplateId"
        >
          确定
        </el-button>
      </template>
    </el-dialog>
  </div>
</template>

<style scoped lang="scss">
.risk-overview-dashboard {
  padding: 0;
}

.page-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 16px;
  padding: 0 4px;

  .header-left {
    h2 {
      margin: 0;
      font-size: 20px;
      font-weight: 600;
      color: #303133;
    }
  }

  .header-right {
    display: flex;
    align-items: center;
    gap: 12px;

    .update-time {
      color: #909399;
      font-size: 12px;
    }
  }
}

.kpi-cards {
  display: grid;
  grid-template-columns: repeat(4, 1fr);
  gap: 16px;
  margin-bottom: 16px;

  .kpi {
    text-align: center;
    padding: 20px;
    transition: all 0.3s;

    &:hover {
      box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
      transform: translateY(-2px);
    }

    .kpi-icon {
      font-size: 32px;
      margin-bottom: 8px;
    }

    .kpi-title {
      color: #909399;
      font-size: 14px;
      margin-bottom: 12px;
    }

    .kpi-value {
      font-size: 32px;
      font-weight: 700;
      color: #303133;
      margin-bottom: 4px;
    }

    .kpi-unit {
      color: #909399;
      font-size: 12px;
      margin-bottom: 8px;
    }

    .kpi-compare {
      color: #909399;
      font-size: 12px;
      margin-top: 8px;
    }
  }
}

.chart-row {
  display: grid;
  grid-template-columns: 1fr 1fr 1fr;
  gap: 16px;
  margin-bottom: 16px;

  .chart-card {
    &.full-width {
      grid-column: 1 / -1;
    }

    .card-header {
      display: flex;
      justify-content: space-between;
      align-items: center;
      font-weight: 600;
      font-size: 16px;

      .header-actions {
        display: flex;
        gap: 8px;
      }
    }
  }
}

.table-card {
  margin-bottom: 16px;

  .card-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    font-weight: 600;
    font-size: 16px;

    .header-actions {
      display: flex;
      gap: 8px;
    }
  }

  .empty-table {
    text-align: center;
    padding: 40px;
    color: #909399;
  }
}

.action-card {
  .action-buttons {
    display: flex;
    gap: 12px;
    // justify-content: 发；;
    flex-wrap: wrap;
  }
}

.score-progress-card {
  .card-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    font-weight: 600;
    font-size: 16px;
  }
}

.score-progress-content {
  .progress-info {
    margin-bottom: 16px;

    .info-item {
      display: flex;
      align-items: center;
      margin-bottom: 8px;

      .label {
        color: #606266;
        font-size: 14px;
        margin-right: 12px;
        width: 80px;
      }

      .value {
        color: #303133;
        font-size: 14px;
        font-family: monospace;
      }
    }
  }

  .progress-stats {
    display: grid;
    grid-template-columns: repeat(2, 1fr);
    gap: 12px;
    margin-top: 16px;

    .stat-item {
      display: flex;
      justify-content: space-between;
      align-items: center;
      padding: 8px 12px;
      background: #f5f7fa;
      border-radius: 4px;

      .stat-label {
        color: #606266;
        font-size: 14px;
      }

      .stat-value {
        font-size: 16px;
        font-weight: 600;
        color: #303133;

        &.success {
          color: #67c23a;
        }

        &.danger {
          color: #f56c6c;
        }
      }
    }
  }
}

@media (max-width: 1400px) {
  .kpi-cards {
    grid-template-columns: repeat(2, 1fr);
  }

  .chart-row {
    grid-template-columns: 1fr;
  }
}
</style>
